const db = uniCloud.database();
const dbCmd = db.command;
const app = getApp();

import utils from '@/common/utils.js'

// 存在问题，如果其中一个步骤出错，无法还原历史数据

function changeStorage(userInfo) {
	return new Promise(function(resolve, reject) {
		app.globalData.userInfo = userInfo;
		resolve(true)
	});
}

function changeDatabase(userInfo) {
	return new Promise(function(resolve, reject) {
		db.collection('uni-id-users').doc(userInfo._id).update({
			balance: userInfo.balance
		}).then(() => {
			resolve(true);
		}).catch(err => {
			reject('changeDatabase fail' + err);
		})
	})

}

function addLog(userInfo, scoresInfo, type) {
	var createDate = new Date();
	return new Promise(function(resolve, reject) {
		db.collection('uni-id-scores')
			.add({
				uid: userInfo._id,
				scores: scoresInfo.scores,
				type: type,
				balance: userInfo.balance,
				comment: scoresInfo.title,
				scoresId: scoresInfo._id,
				create_date: createDate.getTime(),
			})
			.then(() => {
				resolve(true);
			})
			.catch((err) => {
				reject('addLog fail' + err)
			})
	})
}

function giftOrder(userInfo, giftInfo) {
	var createDate = new Date();
	return new Promise(function(resolve, reject) {
		db.collection('giftOrders').add({
				uid: userInfo._id,
				name: userInfo.name,
				create_date: createDate.getTime(),
				giftInfo: giftInfo,
				send: false
			})
			.then((res) => {
				resolve(true)
			})
			.catch((err) => {
				reject('giftOrder fail' + err)
			})
	})

}


function scoresChange(userInfo, scoresInfo, type) {
	return new Promise(function(resolve, reject) {
		// type 1:加积分  2:消费积分
		if (type == 1) {
			if (userInfo.CPC_member && scoresInfo.CPC_activities) {
				// 党员 && 当日活动 不加分
				scoresInfo.scores = 0;
			}
			userInfo.balance = userInfo.balance + scoresInfo.scores;
			Promise
				.all([changeStorage(userInfo), changeDatabase(userInfo), addLog(userInfo, scoresInfo, type)])
				.then(res => {
					resolve(true)
				})
				.catch(err => {
					reject(err)
				})
		} else if (type == 2) {
			userInfo.balance = userInfo.balance - scoresInfo.scores;

			Promise
				.all([changeStorage(userInfo), changeDatabase(userInfo), addLog(userInfo, scoresInfo, type), giftOrder(userInfo,
					scoresInfo)])
				.then(res => {
					resolve(true)
				})
				.catch(err => {
					// TODO 出错以后其他数据回滚
					reject(err)
				})
		}

	})
}


module.exports = {
	scoresChange
}
